package com.antd.admin.server.service.impl;

import cn.hutool.core.util.StrUtil;
import com.antd.admin.api.entity.SysDict;
import com.antd.admin.api.entity.SysDictItem;
import com.antd.admin.api.vo.SysDictTreeVo;
import com.antd.admin.server.mapper.SysDictMapper;
import com.antd.admin.server.service.ISysDictItemService;
import com.antd.admin.server.service.ISysDictService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author 子丶沫
 * @since 2021-06-09
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {
    @Autowired
    private ISysDictItemService dictItemService;
    @Override
    public List<SysDictTreeVo> buildDictTree(String dictName) {
        List<SysDict> dictList = baseMapper.selectList(Wrappers
                .<SysDict>query()
                .lambda()
                .like(StrUtil.isNotBlank(dictName), SysDict::getDictName, dictName)
                .orderByAsc(SysDict::getSort)
        );
        List<SysDictTreeVo> dictTreeVoList= Lists.newArrayList();
        SysDictTreeVo dictTreeVo=null;
        for (SysDict dict : dictList) {
            dictTreeVo=new SysDictTreeVo();
            dictTreeVo.setId(dict.getId());
            dictTreeVo.setTitle(dict.getDictName());
            dictTreeVo.setDictCode(dict.getDictCode());
            dictTreeVo.setDescription(dict.getDescription());
            dictTreeVo.setSort(dict.getSort());
            dictTreeVoList.add(dictTreeVo);
        }
        return dictTreeVoList;
    }

    @Override
    public Boolean deleteDict(Long id) {
        int i = baseMapper.deleteById(id);
        if(i>0){
            dictItemService.remove(Wrappers.<SysDictItem>update().lambda().eq(SysDictItem::getDictId,id));
        }
        return i>0;
    }
}
